package com.example.isoftlangchainai.streamchat;

import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * @Description:stream 第二种实现方式
 * @Date :2025/7/14 16:41
 * @Author :chenjun
 */
@RestController
@RequestMapping("/streamflux")
public class FluxStreamChatController {
    @Value("${langchain4j.open-ai.chat-model.api-key}")
    protected String apikey;
    @Value("${langchain4j.open-ai.chat-model.model-name}")
    protected String modelName;
    @Value("${langchain4j.open-ai.chat-model.base-url}")
    protected String baseUrl;

    /**
     *
     * [描述]: 聊天，流式响应,不支持中文
     */
    @GetMapping(value = "/chat",produces = "text/stream-event;charset=utf-8")
    public Flux<String> streamChat(@RequestParam("message") String message) {
        StreamingChatModel openAiStreamingChatModel = OpenAiStreamingChatModel.builder()
                .baseUrl(baseUrl)
                .apiKey(apikey)
                .modelName(modelName)
                .build();

        Flux<String> flux = Flux.create(fluxSink -> {
            openAiStreamingChatModel.chat(message, new StreamingChatResponseHandler() {
                @Override
                public void onPartialResponse(String partialResponse) {
                    System.out.println("执行时-流式响应：" + partialResponse);
                    fluxSink.next(partialResponse);
                }

                @Override
                public void onCompleteResponse(ChatResponse completeResponse) {
                    System.out.println("完成后-流式响应：" + completeResponse.toString());
                    fluxSink.complete();
                }

                @Override
                public void onError(Throwable error) {
                    System.out.println("执行时-流式响应异常：" + error.getMessage());
                    fluxSink.error(error);
                }
            });
        });
        return flux;
    }

}
